package cn.kgc.springboot.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.kgc.springboot.util.CodeMsg;
import cn.kgc.springboot.util.RedisUtil;
import cn.kgc.springboot.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: hengge
 * @version: v1.0
 * @DATE: 2022/12/1
 * 验证码
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController {

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        //定义图形验证码的长、宽、验证码字符数和干扰元素个数
        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        //获取验证码的文字内容
        String code = lineCaptcha.getCode();
        //此处可以使用redis获取，下述使用session
        request.getSession().setAttribute("code", code);

        //返回一个包含分配给该 session 会话的唯一标识符的字符串。
        String id = request.getSession().getId();
        redisUtil.setValue(id,code,30L, TimeUnit.SECONDS);

        try {
            //写出到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //图形验证码写出，写出到流
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
